<template>
  <el-dialog :title="$t('game.config.betting.dialog.edit')" width="800px" :visible.sync="dialogVisible"
             @close="$emit('update:visible', false)"
             :fullscreen="fullscreen" :class="{'fullscreen': fullscreen}">
    <vue-simplebar>
      <div class="pr-12">
        <el-form :model="dataCache" label-width="85px">
          <el-form-item :label="$t('game.setting.game.name')"
                        :error="Boolean(msg.errors['game_id']) ? msg.errors['game_id'][0] : ''" required>
            <component-page-game-option v-model="dataCache.game_id" :multiple="false"
                                        :disabled="data != null" class="block"
                                        @change="getBetStatus"></component-page-game-option>
          </el-form-item>

          <div>
          <el-form-item :label="$t('game.config.currency.type')"
                        :error="Boolean(msg.errors['bet_type']) ? msg.errors['bet_type'][0] : ''" required>
            <component-page-loading :status="betStatus" @reload="getBetStatus"
                                    ></component-page-loading>
            <el-select :placeholder="$t('game.config.currency.type')"
                       :disabled="!dataCache.config.globals.bet_status" clearable
                       v-model="dataCache.config.globals.bet_type" class="block">
              <el-option v-for="(item, index) in $t('game.data.settlement.bet_type')" :key="index"
                         :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>

          <el-tabs v-model="activeName">
            <el-tab-pane :label="$t('game.setting.config.gameOldConfig')" name="1">
              <el-form-item :label="$t('game.config.betting.config.gear')" :error="error_config_globals_bet"
                            required>
                <el-row class="mb-3" v-for="(bet, i) in dataCache.config.globals.bet1" :key="i">
                  <el-col :span="4">
                    <div v-if="dataCache.config.globals.bet1[i].currency != '_USD'">
                      <component-page-loading :status="currencyListStatus" @reload="getCurrencyList"
                                              v-if="currencyListStatus != 'dle'"></component-page-loading>
                      <el-select :placeholder="$t('game.setting.currency.name')" filterable clearable
                                 v-model="dataCache.config.globals.bet1[i].currency" class="block" v-else>
                        <el-option v-for="item in currencyList" :key="item.currency"
                                   :label="item.currency" :value="item.currency"></el-option>
                      </el-select>
                    </div>
                    <el-input :title="$t('game.config.betting.config.virtual')" :disabled="true"
                              :placeholder="$t('game.config.betting.config.virtual')" v-else></el-input>
                  </el-col>
                  <el-col :span="17" class="pl-2">
                    <el-input :placeholder="$t('game.config.betting.config.gear')"
                              v-for="(item, j) in dataCache.config.globals.bet1[i].gear" :key="j"
                              class="mini"
                              type="number"
                              v-model.number="dataCache.config.globals.bet1[i].gear[j]"></el-input>
                    <el-button class="ml-1" size="small" icon="el-icon-close" circle
                               @click="removeItemOrAdd(dataCache.config.globals.bet1[i].gear, dataCache.config.globals.bet1[i].gear.length - 1, null)"></el-button>
                    <el-button class="ml-1" size="small" icon="el-icon-plus" circle
                               @click="addItem(dataCache.config.globals.bet1[i].gear,null)"></el-button>
                  </el-col>
                  <el-col :span="3" class="text-right">
                    <el-button size="small"
                               @click="removeItemOrAdd(dataCache.config.globals.bet1, i, betItem)">
                      {{ $t('action.delete') }}
                    </el-button>
                    <el-button size="small"
                               @click="addItem(dataCache.config.globals.bet1, dataCache.config.globals.bet1[i])"
                               v-if="dataCache.config.globals.bet1[i].currency != '_USD'">
                      {{ $t('action.copy') }}
                    </el-button>
                  </el-col>
                </el-row>
                <el-button size="small" @click="addItem(dataCache.config.globals.bet1,betItem)">
                  {{ $t('action.add') }}
                </el-button>
                <el-button size="small" @click="addVirtualCurrency" v-if="!isExistVirtualCurrency">
                  {{ $t('action.add') }} {{ $t('platform.config.betting.config.virtual') }}
                </el-button>
              </el-form-item>
            </el-tab-pane>


            <el-tab-pane :label="$t('game.setting.config.gameNewConfig')" name="2">
              <el-form-item :label="$t('game.config.betting.config.gear')" :error="error_config_globals_bet2"
                            required>
                <el-row class="mb-3" v-for="(bet, i) in dataCache.config.globals.bet2" :key="i">
                  <el-col :span="4">
                    <div v-if="dataCache.config.globals.bet2[i].currency != '_USD'">
                      <component-page-loading :status="currencyListStatus" @reload="getCurrencyList"
                                              v-if="currencyListStatus != 'dle'"></component-page-loading>
                      <el-select :placeholder="$t('game.setting.currency.name')" filterable clearable
                                 v-model="dataCache.config.globals.bet2[i].currency" class="block" v-else>
                        <el-option v-for="item in currencyList" :key="item.currency"
                                   :label="item.currency" :value="item.currency"></el-option>
                      </el-select>
                    </div>
                    <el-input :title="$t('game.config.betting.config.virtual')" :disabled="true"
                              :placeholder="$t('game.config.betting.config.virtual')" v-else></el-input>
                  </el-col>
                  <el-col :span="17" class="pl-2">
                    <el-input :placeholder="$t('game.config.betting.config.gear')"
                              v-for="(item, j) in dataCache.config.globals.bet2[i].gear" :key="j"
                              class="mini"
                              type="number"
                              v-model.number="dataCache.config.globals.bet2[i].gear[j]"></el-input>
                    <el-button class="ml-1" size="small" icon="el-icon-close" circle
                               @click="removeItemOrAdd(dataCache.config.globals.bet2[i].gear, dataCache.config.globals.bet2[i].gear.length - 1, null)"></el-button>
                    <el-button class="ml-1" size="small" icon="el-icon-plus" circle
                               @click="addItem(dataCache.config.globals.bet2[i].gear,null)"></el-button>
                  </el-col>
                  <el-col :span="3" class="text-right">
                    <el-button size="small"
                               @click="removeItemOrAdd(dataCache.config.globals.bet2, i, betItem)">
                      {{ $t('action.delete') }}
                    </el-button>
                    <el-button size="small"
                               @click="addItem(dataCache.config.globals.bet2, dataCache.config.globals.bet2[i])"
                               v-if="dataCache.config.globals.bet2[i].currency != '_USD'">
                      {{ $t('action.copy') }}
                    </el-button>
                  </el-col>
                </el-row>
                <el-button size="small" @click="addItem(dataCache.config.globals.bet2,betItem)">
                  {{ $t('action.add') }}
                </el-button>
                <el-button size="small" @click="addVirtualCurrency2" v-if="!isExistVirtualCurrency2">
                  {{ $t('action.add') }} {{ $t('platform.config.betting.config.virtual') }}
                </el-button>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
          </div>


        </el-form>
      </div>
    </vue-simplebar>
    <div slot="title" class="flex justify-between items-center pr-8">
      <div>{{ $t('game.config.betting.dialog.edit') }}</div>
      <div class="operation-icon">
        <i class="el-icon-full-screen float-right" @click="fullscreen = !fullscreen"></i>
      </div>
    </div>
    <div slot="footer">
      <el-button @click="dialogVisible = false">{{ $t('action.cancel') }}</el-button>
      <el-button type="primary" @click="onSubmit">{{ $t('action.save') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "ItemEdit",
  props: ['visible', 'data'],
  data() {
    return {
      activeName: '1',
      dialogVisible: false,
      betStatus: 'dle',
      currencyListStatus: 'dle',
      currencyList: [],
      dataCache: {
        game_id: '',
        config: {
          globals: {
            bet_type: null,
            bet_status: null,
            bet1: [],
            bet2: []
          }
        },
      },
      dataInit: {},
      betItem: {
        'currency': '',
        'gear': [null, null, null, null, null, null]
      },
      msg: {
        code: 200,
        message: '',
        errors: {},
      },
      fullscreen: false,
    }
  },
  computed: {
    error_config_globals_bet: function () {
      for (let key in this.msg.errors) {
        if (_.startsWith(key, 'config.globals.bet1')) {
          return this.msg.errors[key][0];
        }
      }
    },
    error_config_globals_bet2: function () {
      for (let key in this.msg.errors) {
        if (_.startsWith(key, 'config.globals.bet2')) {
          return this.msg.errors[key][0];
        }
      }
    },
    isExistVirtualCurrency: function () {
      if (this.dataCache == null ||
          this.dataCache.config == null ||
          this.dataCache.config.globals == null ||
          this.dataCache.config.globals.bet1 == null) {
        return true;
      }
      for (let item of this.dataCache.config.globals.bet1) {
        if (item.currency == '_USD') {
          return true;
        }
      }
      return false;
    },
    isExistVirtualCurrency2: function () {
      if (this.dataCache == null ||
          this.dataCache.config == null ||
          this.dataCache.config.globals == null ||
          this.dataCache.config.globals.bet2 == null) {
        return true;
      }
      for (let item of this.dataCache.config.globals.bet2) {
        if (item.currency == '_USD') {
          return true;
        }
      }
      return false;
    },
  },
  watch: {
    visible: function (n, o) {
      if (n) {
        console.log(this.data)
        // 初始化参数
        this.initData();
        // 显示模态框
        this.dialogVisible = n;
      }
    }
  },
  created() {
    this.dataInit = _.cloneDeep(this.dataCache);
    // 获取币种列表
    this.getCurrencyList();
  },
  methods: {
    //  获取选中游戏的 bet_status
    getBetStatus() {
      this.dataCache.config.globals.bet_type = null;
      this.betStatus = 'loading';
      // 发起 Ajax 请求
      axios.get('/game/config/betting/getGameDetails', {
        params: {game_id: this.dataCache.game_id}
      }).then(response => {
        // 处理响应数据
        if (response.data.resp_msg.code == 200) {
          this.dataCache.config.globals.bet_status = response.data.resp_data.bet_status;
          this.dataCache.config.globals.bet_type = response.data.resp_data.bet_status == 0 ? 1 : null;
          this.betStatus = 'dle';
        } else {
          this.betStatus = 'error';
        }
      })
    },

    // 获取币种列表
    getCurrencyList() {
      this.currencyListStatus = 'loading';
      axios.get('/common/getCurrencyList', {
        params: {system: true, type: 1}
      }).then((response) => {
        if (response.data.resp_msg.code == 200) {
          this.currencyList = response.data.resp_data;
          this.currencyListStatus = 'dle';
        } else {
          this.currencyListStatus = 'error';
        }
      })
    },

    initMsg() {
      this.msg.code = 200;
      this.msg.message = '';
      this.msg.errors = {};
    },
    initData() {
      this.initMsg();
      if (this.data == null) {
        // 新增
        this.dataCache = _.cloneDeep(this.dataInit);
      } else {
        // 编辑
        this.dataCache = _.cloneDeep(this.data);
        this.dataCache.game_id = this.data.game_id;

        if (this.dataCache.config == null) {
          this.$set(this.dataCache, 'config', {});
        }
        if (this.dataCache.config.globals == null) {
          this.$set(this.dataCache.config, 'globals', {});
        }
        if (this.dataCache.config.globals.bet1 == null) {
          this.$set(this.dataCache.config.globals, 'bet1', []);
        }
        if (this.dataCache.config.globals.bet2 == null) {
          this.$set(this.dataCache.config.globals, 'bet2', []);
        }

        if (this.dataCache.config.globals.bet_status == null) {
          this.$set(this.dataCache.config.globals, 'bet_status', 0);
        }
        if (this.dataCache.config.globals.bet_type == null) {
          this.$set(this.dataCache.config.globals, 'bet_type', 1);
        }
      }
    },
    addVirtualCurrency() {
      this.dataCache.config.globals.bet1.unshift(
          {...this.betItem, ...{currency: '_USD'}}
      );
    },
    addVirtualCurrency2() {
      this.dataCache.config.globals.bet2.unshift(
          {...this.betItem, ...{currency: '_USD'}}
      );
    },
    addItem(configs, item) {
      this.$nextTick(function (){
        configs.push(_.cloneDeep(item));
      });
    },
    removeItem(configs, index) {
      configs.splice(index, 1);
    },
    removeItemOrAdd(configs, index, item) {
      this.removeItem(configs, index);
      // if (!configs.length) {
      //   this.addItem(configs, item);
      // }
    },
    onSubmit() {
      this.initMsg();
      // loading 状态 start
      let loading = this.$loading();
      // 保存数据
      axios.post('/game/config/betting/save', this.dataCache).then((response) => {
        // loading 状态 close
        loading.close();
        // 逻辑处理
        if (response.data.resp_msg.code == 200) {
          this.$message({
            type: 'success',
            message: this.$t('messages.succeeded', {status: this.$t('action.save')}),
            showClose: true
          });
          this.dialogVisible = false;
          // 广播事件到父组件
          this.$emit('edit');
        } else if (_.includes([42000, 44202], response.data.resp_msg.code)) {
          this.$message({
            type: 'error',
            message: response.data.resp_msg.message,
            showClose: true
          });
          this.msg = response.data.resp_msg;
        } else {
          this.$message({
            type: 'error',
            dangerouslyUseHTMLString: true,
            message: this.$t('messages.failed', {status: this.$t('action.save')}) + `<div class="mt-2">${response.data.resp_msg.message}</div>`,
            showClose: true
          });
        }
      })
    },
  }
}
</script>

<style scoped>
::v-deep .el-dialog__body {
  padding-top: 15px;
  padding-bottom: 15px;
  height: 600px;
}

::v-deep.fullscreen .el-dialog__body {
  height: calc(100vh - 125px);
}
</style>
